#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include "temp.h"
#include "led.h"
#include "tcp.h"

// about pins define ,look here(https://github.com/BPI-SINOVOIP/BPI-WiringPi2/blob/master/pins/pins.pdf)
// about *.h file ,look here(/usr/include/wiring*)
// about color ,look here(http://bbs.csdn.net/topics/100170382)
// wiringPi can not used to led control, because wiringPi only used to CON1.

int g_iCpuTemp  = 0;
int g_iSendTime = 0;
extern struct ledControl leds;
int main(int argc,char *argv[])
{
	char buffer[200];
	if( argc != 3){  
    printf("usage: ./iotTest <ipaddress> <port>\n");  
    exit(0);  
    } 
	// Used wiringPi
	wiringPiSetup();
	pinMode(2, OUTPUT);
	ConnectToSvr(argv[1],atoi(argv[2]));  //connect to server
	printf("\n\n");
	for(;;)
	{
		if(leds.manualControl==0){
			digitalWrite(2, HIGH);  // Used wiringPi to control gpio 
			SetLed(LEDB,ON);
			SetLed(LEDG,OFF);
			delay(500);
			digitalWrite(2, LOW);
			SetLed(LEDB,OFF);
			SetLed(LEDG,ON);
			delay(500);
			g_iCpuTemp = GetTemp();  // Get temperature
			sprintf(buffer,"CPU temperature is %d",g_iCpuTemp);
			SendData(buffer);
			//printf("\33[1A" "[\33[31;40m Auto Controling \33[0m] CPU temperature is [\33[31;40m%d\33[0m]\n",g_iCpuTemp);
		}else{
			if(leds.refresh==1)
			{
				if(leds.iGreenLedStat==1)
				{
					SetLed(LEDG,ON);
				}else{
					SetLed(LEDG,OFF);
				}
				if(leds.iBlueLedStat==1)
				{
					SetLed(LEDB,ON);
				}else{
					SetLed(LEDB,OFF);
				}
				leds.refresh=0;
			}
			delay(100);
			g_iSendTime+=1;
			if(g_iSendTime%10==0)
			{
				g_iCpuTemp = GetTemp();  // Get temperature
				sprintf(buffer,"CPU temperature is %d",g_iCpuTemp);
				SendData(buffer);
				printf("\33[1A" "[\33[31;40m Manual Controling \33[0m] CPU temperature is [\33[31;40m%d\33[0m]\n",g_iCpuTemp);
			}
		}
		
		if(leds.exitFlag==1)
		{
			break;
		}
	}
	DisconectSvr();
	printf("Exit\n");
	return 0;
}


